package com.syx.friend.Service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.syx.commoncore.Constant.Constant;
import com.syx.commoncore.Model.Result;
import com.syx.commoncore.Model.TableDataInfoResult;
import com.syx.commoncore.Utils.ThreadLocalUtil;
import com.syx.commoncore.enums.ExamListType;
import com.syx.commoncore.enums.Resultcode;
import com.syx.friend.Manager.ExamCacheManager;
import com.syx.friend.Mapper.ExamMapper;
import com.syx.friend.Mapper.UserExamMapper;
import com.syx.friend.Mapper.UserMapper;
import com.syx.friend.Model.exam.DTO.ExamDTO;
import com.syx.friend.Model.exam.DTO.ExamQueryDTO;
import com.syx.friend.Model.exam.Exam;
import com.syx.friend.Model.exam.VO.ExamVO;
import com.syx.friend.Model.user.UserExam;
import com.syx.friend.Service.IUserExamService;
import com.syx.security.Exception.ServiceException;
import com.syx.security.Service.TokenService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class IUserExamServiceImpl implements IUserExamService {

    @Value("${jwt.secret}")
    private String secret;

    @Resource
    UserMapper userMapper;

    @Resource
    TokenService tokenService;
    @Resource
    ExamMapper examMapper;

    @Resource
    UserExamMapper userExamMapper;

    @Resource
    ExamCacheManager examCacheManager;


    @Override
    public Result<Void> enter(ExamDTO examDTO, String token) {
        Exam exam = examMapper.selectById(examDTO.getExamId());
        if (exam == null) {
            throw new ServiceException(Resultcode.EXAM_NOT_EXIST);

        }
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(Resultcode.EXAM_STARTED);
        }
        Long userId = ThreadLocalUtil.get(Constant.USER_ID, Long.class);
        System.out.println(userId);
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>().eq(UserExam::getExamId, examDTO.getExamId()).eq(UserExam::getUserId, userId));
        if (userExam != null) {
            throw new ServiceException(Resultcode.USER_EXAM_HAS_ENTER);
        }
        //存入用户Id
        //插入userId对应的题目Id。
        examCacheManager.addUserExamCache(userId, examDTO.getExamId());
        UserExam insertUserExam = new UserExam();
        insertUserExam.setExamId(examDTO.getExamId());
        insertUserExam.setUserId(userId);
        int insert = userExamMapper.insert(insertUserExam);
        if (insert != 1) {
            throw new ServiceException(Resultcode.FAILED);
        }


        return Result.success();


    }

    @Override
    public TableDataInfoResult list(ExamQueryDTO examQueryDTO) {
        //先查询缓存uel 如果查不到再到数据库中查询，并且把数据库中的数据放入redis中
        Long userId = ThreadLocalUtil.get(Constant.USER_ID, Long.class);
        System.out.println(userId);
        Long listSize = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        //redis查不到的时候就在 数据库中查找
        System.out.println(listSize);
        if (listSize == null || listSize <= 0) {
            //如果没有数据就调用上面的方法进行查找，并且刷新到redis中
            List<ExamVO> examVOList = userExamMapper.selectUserExamList(userId);

            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
            return TableDataInfoResult.success(examVOList, examVOList.size());

        } else {
            examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
            List<ExamVO> examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            //
            listSize = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId );
            if (CollectionUtil.isEmpty(examVOList)) {
                return TableDataInfoResult.empty();
            }
            return TableDataInfoResult.success(examVOList, listSize);

        }
    }
}
